<template>
	<view class="zy-modal" :class="dshow?'show':''" @tap.stop="testFn($event)">
		<view class="zy-dialog" style="background-color: transparent;">
			<view class="padding-top text-white" :class="'zy-upgrade-topbg-'+theme" :style="'background-image:url('+imageList[theme]+')'">
				<view>
					<text class="zy-upgrade-title">
						发现新版本
					</text>
				</view>
				<text class="flex-wrap">{{version}}</text>
			</view>
			<view class="padding-xl bg-white text-left">
				<scroll-view style="max-height: 200rpx;" scroll-y="auto" v-if="!update_flag">
					<text>{{update_tips}}</text>
				</scroll-view>
				<view class="zy-progress radius striped active" v-if="update_flag">
					<view :class="'bg-'+theme" :style="'width: '+update_process+'%;'">
						{{update_process}}%
					</view>
				</view>
			</view>
			<view class="zy-bar bg-white justify-end">
				<view class="action" v-if="!update_flag">
					<button class="zy-btn" :class="'bg-'+theme" @click="upgrade_checked">确认升级</button>
					<button class="zy-btn margin-left" :class="'line-'+theme" v-if="enforcement_upgrade !=1"
						@click="upgrade_cancel">取消升级</button>
				</view>
				<view class="action text-center" v-if="update_flag&&!forceupgrade">
					<button class="zy-btn" :class="'bg-'+theme" @click="upgrade_break">中断升级</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		SERVICE_URL
	} from '@/config/index.js'
	import {
		appid,
		version
	} from '@/config/index.js'
	import {
		getAppUpdateInfo
	} from '@/api/site.js'
	import image1 from '@/static/images/upgrade/green.png'
	import image2 from '@/static/images/upgrade/red.png'
	import image3 from '@/static/images/upgrade/pink.png'
	import image4 from '@/static/images/upgrade/yellow.png'
	import image5 from '@/static/images/upgrade/blue.png'
	export default {
		name: 'ZyUpgrade',
		props: {
			theme: { //主题，目前支持green,pink,blue,yellow,red
				type: String,
				default: 'green'
			},
			updateurl: { //升级检测url，全路径
				type: String,
				default: ''
			},
			h5preview: { //H5界面下是否预览升级
				type: Boolean,
				default: true
			},
			oldversion: { //如果是H5，为了方便测试，可以传入一个旧版本号进来。
				type: String,
				default: ''
			},
			oldcode: { //如果是H5，为了方便测试，可以传一个旧版本的code进来。
				type: Number,
				default: 0
			},
			appstoreflag: { //是否启用appstore升级，如果启用，由服务端返回appstore的地址
				type: Boolean,
				default: false
			},
			noticeflag: { //是否通知主界面无需更新
				type: Boolean,
				default: false
			},
			autocheckupdate: { //是否页面截入时就判断升级
				type: Boolean,
				default: true
			},
			showUpdate: { //是否显示
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				update_flag: false, //点击升级按钮后，显示进度条
				dshow: false,
				update_process: 0,
				downloadTask: [],
				updated2version: '',
				version_url: '',
				update_tips: '',
				forceupgrade: false,
				currentversion: this.oldversion,
				versionname: '',
				vesioncode: this.oldcode,
				wgt_flag: 0,
				wgt_url: '',
				app_verurl: '',
				ver_sion: '',
				enforcement_upgrade: '',
				enforcement_flag: '',
				version: '',
				size: 0, //开启gzip等情形下，获取不到安装包大小，可以服务端返回安装包大小
				updateTime: '',
				stopTime: '',
				imageList: {
					'green': image1,
					'red': image2,
					'pink': image3,
					'yellow': image4,
					'blue': image5
				}
			}
		},
		mounted() {
			let app_flag = false
			// #ifdef APP-PLUS
			app_flag = true
			// #endif
			if ((this.h5preview || app_flag) && this.autocheckupdate) {
				this.check_update()
			}
		},
		computed: {
			v_ersion() {
				let retversion = ''
				retversion = this.currentversion + (this.currentversion != '' && this.updated2version != '' ? '->' : '') +
					this.updated2version
				return retversion
			},
		},
		created() {
			this.androidCheckUpdate()
		},
		onShow() {
			this.androidCheckUpdate()
		},
		methods: {
			addDate() {
				const nowDate = new Date();
				const date = {
					year: nowDate.getFullYear(),
					month: nowDate.getMonth() + 1,
					date: nowDate.getDate(),
				}
				const newmonth = date.month > 10 ? date.month : '0' + date.month
				const day = date.date > 10 ? date.date : '0' + date.date
				this.updateTime = date.year + '-' + newmonth + '-' + day
			},
			stopDate() {
				const nowDate = new Date();
				const date = {
					year: nowDate.getFullYear(),
					month: nowDate.getMonth() + 1,
					date: nowDate.getDate() + 3,
				}
				const newmonth = date.month > 10 ? date.month : '0' + date.month
				const day = date.date > 10 ? date.date : '0' + date.date
				this.stopTime = date.year + '-' + newmonth + '-' + day
				uni.setStorageSync('stopTime', this.stopTime)
			},
			testFn(e) {
				e.preventDefault();
			},
			//点击取消升级按钮，取消升级
			upgrade_cancel: function() {
				this.stopDate()
				this.dshow = false
				this.$emit('showUpdate', false)
				uni.showTabBar()
				uni.setStorageSync("cancel_upgrade", 1)
				uni.setStorageSync('cancel_verson', this.ver_sion)
			},
			async androidCheckUpdate() {
				this.addDate()
				let status = false;
				let stopTime = uni.getStorageSync('stopTime')
				let Date1 = new Date(this.updateTime);
				let Date2 = new Date(stopTime);
				let Date3 = new Date(stopTime).getTime()+86400000;
				await getAppUpdateInfo({
					appid,
					version
				}).then(res => {
					const {
						data
					} = res
					if (res.data != '') {
						this.content = data.content
						this.app_verurl = data.update_url
						this.ver_sion = data.version
						this.enforcement_upgrade = data.enforcement_upgrade
						if(this.enforcement_upgrade == '1'){
							uni.removeStorageSync('stopTime')
						}
						getApp().globalData.enforcement_upgrade = this.enforcement_upgrade
						this.newVersion = data.version
						this.version = data.version
						this.update_tips = res.data.content
					}
					uni.setStorageSync("enforcement_upgrade", this.enforcement_upgrade)
					if (data.enforcement_upgrade === '1') {
						status = true
						let enforcement_upgrade = getApp().globalData.enforcement_upgrade
						uni.setStorageSync("enforcement_upgrade", enforcement_upgrade)
					}
					if (data.enforcement_upgrade === '0') {
						uni.setStorageSync("enforcement_upgrade", 0)
					}
					if (version < data.version) {
						status = true
					}
					let upgrade = uni.getStorageSync("cancel_upgrade")
					
					if(upgrade == 1 && data.enforcement_upgrade == 0){
						status = false
					}
					if(stopTime != ''){
						if(Date1.getTime()> Date3){
							uni.setStorageSync("cancel_upgrade", 0)
						}
						if (Date1.getTime() > Date2.getTime()) {
							status = true
							uni.removeStorageSync('stopTime')
						}
						if (Date1.getTime() < Date2.getTime()) {
							status = false
						}
					}
					let cancel_verson = uni.getStorageSync('cancel_verson')
					if (cancel_verson && cancel_verson < data.version) {
						status = true
					}
					if (status) {
						this.dshow = true
						this.$emit('showUpdate', true)
						// uni.hideTabBar()
					} else {
						this.dshow = false
						this.$emit('showUpdate', false)
						uni.showTabBar()
					}
				}).catch(err => {
					this.dshow = false
					this.$emit('showUpdate', false)
					uni.showTabBar()
				})
			},
			test() {
				uni.downloadFile({
					url: SERVICE_URL + '/apk/app-un%7E1_signed.apk', //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							//下载成功
						}
					}
				});
			},
			//检测升级
			check_update() {
				let that = this
				// #ifdef APP-PLUS
				plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
					that.currentversion = widgetInfo.version
					that.versionname = widgetInfo.name
					that.versioncode = widgetInfo.versionCode
					that.updatebusiness(that)
				});
				// #endif
				// #ifdef H5
				if (this.h5preview) {
					this.updatebusiness(that)
				}
				// #endif
			},

			updatebusiness: function(that) { //具体升级的业务逻辑
				// uni.showLoading({
				// 	title: '',
				// 	mask: false
				// });
				let platform = uni.getSystemInfoSync().platform
				let formdata = {
					method: "upgrade",
					version: that.currentversion,
					name: that.versionname,
					code: that.versioncode,
					ts: (new Date()).valueOf(),
					transid: '123',
					sign: '123',
					platform: platform
				}
				return false
				uni.request({
					url: that.updateurl,
					data: formdata,
					success: (result) => {
						uni.hideLoading()
						let data = result.data
						if (data.code == 100) {
							//提示升级
							if (data.data.update_flag == 1) {
								that.dshow = true
								that.$emit('showUpdate', true)
								// uni.hideTabBar()
								that.update_tips = data.data.update_tips
								that.forceupgrade = data.data.forceupdate == 1
								that.version_url = data.data.update_url
								that.updated2version = data.data.version
								that.wgt_flag = data.data.wgt_flag
								that.wgt_url = data.data.wgt_url
								that.size = data.data.size
							} else {
								if (that.noticeflag) {
									//通知父组件，当前版为最新版本
									that.$emit("showupdateTips", 0)
								}
							}
						} else {
							uni.showToast({
								title: '请求升级出错：' + data.msg,
								icon: 'none'
							});
						}
					}
				});
			},

			//点击开始升级按钮，开始升级
			upgrade_checked: function() {
				this.update_flag = true
				this.updateversion()
				uni.setStorageSync("enforcement_upgrade", '0')
				uni.setStorageSync('upStorage','0')
				// uni.hideTabBar()
			},
			//升级过程中，点击中断升级按钮，中断升级
			upgrade_break: function() {
				this.downloadTask.abort()
				this.update_flag = false
			},

			//升级下载apk安装包的具体处理业务逻辑
			updateversion: function() {
				let platform = uni.getSystemInfoSync().platform
				let that = this
				let downloadurl = this.app_verurl
				this.update_confirm = true
				this.downloadTask = uni.downloadFile({
					url: this.app_verurl,
					success: function(res) {
						if (res.statusCode == 200) {
							//开始安装
							plus.runtime.install(res.tempFilePath, {
								force: false
							}, function() {
								plus.runtime.restart();
							}, function(e) {
								uni.showToast({
									title: '升级失败',
									icon: 'none'
								});
							});
						} else {
							uni.showToast({
								title: '下载失败，网络错误',
								icon: 'none'
							});
						}
					},
					fail: function(e) {
						uni.showToast({
							title: '下载失败:' + e.errMsg,
							icon: 'none'
						});
						this.update_flag = false
					},
					complete: function() {}
				})
				this.downloadTask.onProgressUpdate(function(res) {
					that.update_process = res.progress
					if (res.progress == Infinity) {
						//使用size计算
						let progress = (res.totalBytesWritten / that.size) * 100
						if (progress > 100) {
							progress = 100
						}
						that.update_process = progress
					}
				})

			},
		}
	}
</script>

<style scoped>
	@import url("static/css/main.css");

	.zy-upgrade-topbg-green {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		height: 290rpx;
	}

	.zy-upgrade-topbg-red {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		height: 290rpx;
	}

	.zy-upgrade-topbg-pink {
		background-image: url();
		background-size: 100% 100%;
		background-repeat: no-repeat;
		height: 290rpx;
	}

	.zy-upgrade-topbg-yellow {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		height: 290rpx;
	}

	.zy-upgrade-topbg-blue {
		background-size: 100% 100%;
		background-repeat: no-repeat;
		height: 290rpx;
	}

	.zy-upgrade-title {
		font-size: 50rpx;
		color: white;
	}
</style>
